use cross_rs::IResult;
use cross_rs::fasttime::b2_time::TimeFT;

use super::sqlite_db::SqliteDb;


/// 可写入sqltie
pub trait ISqlitable {
    fn sql_建表(table: Option<String>) -> (String, String);
    fn sql_插入_0(&self) -> String;
    fn sql_插入_1(&self, table: &str) -> String;

    // fn fill_row(&mut self, row: &rusqlite::Row<'_>) -> Result<(), rusqlite::Error>;
}




pub fn save_sqlite<T: ISqlitable>(file_sqlite: &str, list_rows: &Vec<T>, table: Option<String>) -> IResult<(TimeFT, f64)> {
    let start = TimeFT::now();

    let list_表名_sql建表 = vec![T::sql_建表(table.clone())];
    let mut db = SqliteDb::new(file_sqlite.to_string(), "".to_string());
    db.crate_创建多个表格(&list_表名_sql建表)?;
    if list_rows.len() < 1 {
        return Ok((start, 0.1));
    }
    let mut list_sql_插入 = vec![];

    if let Some(表名) = table {
        for row in list_rows {
            let sql_插入 = row.sql_插入_1(&表名);
            list_sql_插入.push(sql_插入);
            if list_sql_插入.len() == SqliteDb::COUNT_PER_PAGE {
                db.insert_插入许多(&list_sql_插入)?;
                list_sql_插入.clear();
            }
        }
        if list_sql_插入.len() > 0 {
            db.insert_插入许多(&list_sql_插入)?;
            list_sql_插入.clear();
        }
    } else {
        for row in list_rows {
            let sql_插入 = row.sql_插入_0();
            list_sql_插入.push(sql_插入);
            if list_sql_插入.len() == SqliteDb::COUNT_PER_PAGE {
                db.insert_插入许多(&list_sql_插入)?;
                list_sql_插入.clear();
            }
        }
        if list_sql_插入.len() > 0 {
            db.insert_插入许多(&list_sql_插入)?;
            list_sql_插入.clear();
        }
    }

    let secs = TimeFT::now().seconds_from(&start);

    Ok((start, secs))
}


pub fn save_sqlite_blob<T: ISqlitable>(file_sqlite: &str, list_rows: &Vec<T>) -> IResult<(TimeFT, f64)> {
    let start = TimeFT::now();

    let list_表名_sql建表 = vec![T::sql_建表(None)];
    let mut db = SqliteDb::new(file_sqlite.to_string(), "".to_string());
    db.crate_创建多个表格(&list_表名_sql建表)?;
    let mut list_sql_插入 = vec![];
    for row in list_rows {
        let sql_插入 = row.sql_插入_0();
        list_sql_插入.push(sql_插入);
        if list_sql_插入.len() == SqliteDb::COUNT_PER_PAGE {
            db.insert_插入许多(&list_sql_插入)?;
            list_sql_插入.clear();
        }
    }
    if list_sql_插入.len() > 0 {
        db.insert_插入许多(&list_sql_插入)?;
        list_sql_插入.clear();
    }
    let secs = TimeFT::now().seconds_from(&start);

    Ok((start, secs))
}

pub fn qeury_i64_values(file_sqlite: &str, sql_select: &str) -> IResult<Vec<i64>> {
    let conn = rusqlite::Connection::open(file_sqlite)?;
    
    let mut stmt = conn.prepare(sql_select)?;
    let items_iter = stmt.query_map([], |row| {
        let v_i64: i64 = row.get(0)?;
        Ok(v_i64)
    })?;
    let mut list_values = vec![];
    for item in items_iter {
        list_values.push(item?);
    }
    Ok(list_values)

}

